package com.kexin.student.service.impl;

import java.util.List;
import com.kexin.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kexin.student.mapper.StudeptMapper;
import com.kexin.student.domain.Studept;
import com.kexin.student.service.IStudeptService;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kexin.common.annotation.DataScope;
import com.kexin.common.constant.UserConstants;
import com.kexin.common.core.domain.TreeSelect;
import com.kexin.common.core.domain.entity.SysDept;
import com.kexin.common.core.domain.entity.SysRole;
import com.kexin.common.core.domain.entity.SysUser;
import com.kexin.common.core.text.Convert;
import com.kexin.common.exception.ServiceException;
import com.kexin.common.utils.SecurityUtils;
import com.kexin.common.utils.StringUtils;
import com.kexin.common.utils.spring.SpringUtils;
import com.kexin.system.mapper.SysDeptMapper;
import com.kexin.system.mapper.SysRoleMapper;
import com.kexin.system.service.ISysDeptService;

/**
 * 学生部门Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-17
 */
@Service
public class StudeptServiceImpl implements IStudeptService
{
    @Autowired
    private StudeptMapper studeptMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    /**
     * 查询部门管理数据
     *
     * @param studept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Studept> selectStudeptList(Studept studept)
    {
        return studeptMapper.selectStudeptList(studept);
    }

    /**
     * 查询部门树结构信息
     *
     * @param studept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectStudeptTreeList(Studept studept)
    {
        List<Studept> studepts = SpringUtils.getAopProxy(this).selectStudeptList(studept);
        return buildStudeptTreeSelect(studepts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param studepts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<Studept> buildStudeptTree(List<Studept> studepts)
    {
        List<Studept> returnList = new ArrayList<Studept>();
        List<Long> tempList = studepts.stream().map(Studept::getDeptId).collect(Collectors.toList());
        for (Studept studept : studepts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(studept.getParentId()))
            {
                recursionFn(studepts, studept);
                returnList.add(studept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = studepts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param studepts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildStudeptTreeSelect(List<Studept> studepts)
    {
        List<Studept> studeptTrees = buildStudeptTree(studepts);
        return studeptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
//    @Override
//    public List<Long> selectStudeptListByRoleId(Long roleId)
//    {
//        SysRole role = roleMapper.selectRoleById(roleId);
//        return studeptMapper.selectStudeptListByRoleId(roleId, role.isStudeptCheckStrictly());
//    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public Studept selectStudeptById(Long deptId)
    {
        return studeptMapper.selectStudeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenStudeptById(Long deptId)
    {
        return studeptMapper.selectNormalChildrenStudeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = studeptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkStudeptExistUser(Long deptId)
    {
        int result = studeptMapper.checkStudeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param studept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkStudeptNameUnique(Studept studept)
    {
        Long deptId = StringUtils.isNull(studept.getDeptId()) ? -1L : studept.getDeptId();
        Studept info = studeptMapper.checkStudeptNameUnique(studept.getDeptName(), studept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkStudeptDataScope(Long deptId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && StringUtils.isNotNull(deptId))
        {
            Studept studept = new Studept();
            studept.setDeptId(deptId);
            List<Studept> studepts = SpringUtils.getAopProxy(this).selectStudeptList(studept);
            if (StringUtils.isEmpty(studepts))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param studept 部门信息
     * @return 结果
     */
    @Override
    public int insertStudept(Studept studept)
    {
        Studept info = studeptMapper.selectStudeptById(studept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        studept.setAncestors(info.getAncestors() + "," + studept.getParentId());
        return studeptMapper.insertStudept(studept);
    }

    /**
     * 修改保存部门信息
     *
     * @param studept 部门信息
     * @return 结果
     */
    @Override
    public int updateStudept(Studept studept)
    {
        Studept newParentStudept = studeptMapper.selectStudeptById(studept.getParentId());
        Studept oldStudept = studeptMapper.selectStudeptById(studept.getDeptId());
        if (StringUtils.isNotNull(newParentStudept) && StringUtils.isNotNull(oldStudept))
        {
            String newAncestors = newParentStudept.getAncestors() + "," + newParentStudept.getDeptId();
            String oldAncestors = oldStudept.getAncestors();
            studept.setAncestors(newAncestors);
            updateStudeptChildren(studept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = studeptMapper.updateStudept(studept);
        if (UserConstants.DEPT_NORMAL.equals(studept.getStatus()) && StringUtils.isNotEmpty(studept.getAncestors())
                && !StringUtils.equals("0", studept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentStudeptStatusNormal(studept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param studept 当前部门
     */
    private void updateParentStudeptStatusNormal(Studept studept)
    {
        String ancestors = studept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        studeptMapper.updateStudeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateStudeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<Studept> children = studeptMapper.selectChildrenStudeptById(deptId);
        for (Studept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            studeptMapper.updateStudeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteStudeptById(Long deptId)
    {
        return studeptMapper.deleteStudeptById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Studept> list, Studept t)
    {
        // 得到子节点列表
        List<Studept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Studept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Studept> getChildList(List<Studept> list, Studept t)
    {
        List<Studept> tlist = new ArrayList<Studept>();
        Iterator<Studept> it = list.iterator();
        while (it.hasNext())
        {
            Studept n = (Studept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Studept> list, Studept t)
    {
        return getChildList(list, t).size() > 0;
    }
}